package com.lyhengtongwl.zqsnews.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.entity.BaseEntity;
import com.lyhengtongwl.zqsnews.entity.UserInfoEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.DataCleanManager;
import com.lyhengtongwl.zqsnews.utils.FileUtils;
import com.lyhengtongwl.zqsnews.utils.GsonUtils;
import com.lyhengtongwl.zqsnews.utils.PermissionUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.lyhengtongwl.zqsnews.utils.ToastUtil;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;
import retrofit2.Response;

/**
 * 设置
 */
public class SettingActivity extends BaseActivity {

    private static final int TAKE_PHOTO_CODE = 1;
    private static final int PICK_PHOTO_CODE = 2;
    private static final int EDIT_NICKNAME = 3;

    @BindView(R.id.iv_myhead)
    ImageView ivMyhead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_cache)
    TextView tv_cache;
    private Context mContext;
    UserInfoEntity userInfo = null;

    @Override
    public void setListen() {

    }

    @Override
    public void setTitleBarColor() {
        new TitleBuilder(this).setTitleText("设置")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_setting;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {
        mContext = this;
        try {
            tv_cache.setText("缓存：" + DataCleanManager.getTotalCacheSize(App.getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initData() {
        accountReset();
    }

    @OnClick({R.id.rl_nickname, R.id.rl_aboutus, R.id.clear, R.id.iv_myhead, R.id.rel_clear})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_myhead://修改头像
                showSelectDialog();
                break;
            case R.id.rl_nickname://修改昵称
                startActivityForResult(new Intent(this, EditnameActivity.class)
                        .putExtra("nickname", userInfo.getUserNickname()), EDIT_NICKNAME);
                break;
            case R.id.rl_aboutus:
                if (userInfo != null) {
                    startActivity(new Intent(this, WebActivity.class)
                            .putExtra("url", userInfo.getAboutUs())
                            .putExtra("title", "关于我们"));
                } else {
                    ToastUtil.showShort(this, "获取用户信息失败");
                }
                break;
            case R.id.clear://退出登录
                new CenterDialog(R.layout.prompt_dialog, SettingActivity.this).showPrompt("确认退出？");
                break;
            case R.id.rel_clear://清除缓存
                new CenterDialog(R.layout.prompt_dialog, SettingActivity.this).showPrompt(tv_cache);
                break;
        }
    }

    /**
     * 选择照片弹窗
     */
    private void showSelectDialog() {
        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(this.getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                //照相
                v.findViewById(R.id.tv_takephoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (PermissionUtils.getInstance().checkPermission(SettingActivity.this,
                                Manifest.permission.CAMERA)) {
                            File myhead = new File(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri uri = FileProvider.getUriForFile(SettingActivity.this,
                                    getPackageName() + ".provider", myhead);
                            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(it, TAKE_PHOTO_CODE);
                        } else {
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(SettingActivity.this);
                        }
                        bottomDialog.dismiss();
                    }
                });
                //选择照片
                v.findViewById(R.id.tv_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(Intent.ACTION_PICK, null);
                        it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(it, PICK_PHOTO_CODE);
                        bottomDialog.dismiss();
                    }
                });

                //取消
                v.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

            }
        }).setLayoutRes(R.layout.select_change_image)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择图片
        if (requestCode == PICK_PHOTO_CODE && resultCode == RESULT_OK) {
            if (data.getData() != null) {
                Log.i("路径", "路径为：" + FileUtils.getFilePath(this, data.getData()));
                ///storage/emulated/0/Pictures/Screenshots/Screenshot_20190123-214734.jpg
                //上传图片
                if (FileUtils.getFilePath(this, data.getData()) != null) {
//                    uploadImg(FileUtils.getFilePath(this, data.getData()));
                } else {
                    ToastUtil.showShort(this, "文件不存在");
                }
            }
        }

        //拍照
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            File temp = new File(Constant.DIR_INFO.APP_DIR + "/head.jpg");
            if (temp.exists()) {
//                uploadImg(FileUtils.getFilePath(this, Uri.fromFile(temp)));
            } else {
                ToastUtil.showShort(this, "文件不存在");
            }
        }

        //修改昵称
        if (requestCode == EDIT_NICKNAME && resultCode == RESULT_OK) {
            String nickname = data.getStringExtra("nickname");
            tvNickname.setText(nickname);
        }

    }

    /**
     * 获取个人信息
     */
    private void accountReset() {
        Task.getApiService().getAccountInfo().enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        userInfo = GsonUtils.parseJSON(response.body().getResult().toString(),
                                UserInfoEntity.class);
                        if (userInfo != null) {
                            Glide.with(mContext).load(userInfo.getUserAvatar())
                                    .into(ivMyhead);

                            tvNickname.setText(userInfo.getUserNickname());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }

    /**
     * 上传图片到阿里OSS服务
     */
//    private void uploadImg(String imgPath) {
//        String userid = SPUtils.get(getApplicationContext(), Constant.UserInfo.ID, "").toString();
//        final String pathName = "avatar/userid_" + userid + "_" + System.currentTimeMillis() + ".png";//服务器地址
//        Log.i("pathName", pathName);
//
//        //构造上传请求
//        String backetName = SPUtils.get(getApplicationContext(), Constant.AliOOS.BACKET_NAME, "").toString();
//        PutObjectRequest put = new PutObjectRequest(backetName, pathName, imgPath);
//        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
//            @Override
//            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
//            }
//        });
//        App.getOSS().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
//            @Override
//            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                Log.i("PutObject", "UploadSuccess");
//                String domain = SPUtils.get(getApplicationContext(), Constant.AliOOS.DOMAIN, "").toString();
//                String headPath = domain + File.separator + pathName;
//                editUserInfo(headPath);
//            }
//
//            @Override
//            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
//                // 请求异常
//                if (clientException != null) {
//                    // 本地异常如网络异常等
//                    clientException.printStackTrace();
//                }
//                if (serviceException != null) {
//                    // 服务异常
//                    Log.e("ErrorCode", serviceException.getErrorCode());
//                    Log.e("RequestId", serviceException.getRequestId());
//                    Log.e("HostId", serviceException.getHostId());
//                    Log.e("RawMessage", serviceException.getRawMessage());
//                }
//            }
//        });
//    }

    /**
     * 修改头像
     */
    private void editUserInfo(final String headPath) {
        Task.getApiService().editMyInfo("", headPath).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    ToastUtil.showShort(SettingActivity.this, response.body().getMessage());
                    if ("0".equals(response.body().getCode())) {
                        Glide.with(mContext).load(headPath)
                                .into(ivMyhead);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }


}
